from .trigger import AlertTrigger


# 联动进入报警器
class CountTrigger(AlertTrigger):
    _operator_map = {
        '等于': '==',
        '不等于': '!=',
        '大于': '>',
        '大于等于': '>=',
        '小于': '<',
        '小于等于': '<=',
    }

    def __init__(self, event, object, operator, count=None):
        super().__init__(event, object)
        assert count is not None, '必须传入物体数量参数'
        assert count >= 0, '时间物体数量必须大于等于0'
        assert operator in self._operator_map, '运算符必须是[等于、不等于、大于、大于等于、小于、小于等于]中的一个'
        self._condition_code = f'{self._operator_map[operator]}{count}'
        self._alerted = False  # 表示当前条件是否已经报警，避免一直满足条件一直报警
    
    def _update(self, obj, objs, image):
        if eval(str(len(objs)) + self._condition_code):
            if not self._alerted:
                image = image.copy()
                for o in objs:
                    o.make_shotcut(image)
                self._alert(objs, image)
                self._alerted = True
        else:
            self._alerted = False

    def enter(self, obj, objs, image):
        self._update(obj, objs, image)

    def leave(self, obj, objs, image):
        self._update(obj, objs, image)
